//
//  PhotoView.m
//  PhotoBrowse
//
//  Created by 邹功梁 on 15/10/26.
//  Copyright © 2015年 邹功梁. All rights reserved.
//

#import "PhotoView.h"
#import "MKBaseHeader.h"
@implementation PhotoView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _scrollView = [[UIScrollView alloc] initWithFrame:frame];
        _scrollView.delegate = self;
        _scrollView.maximumZoomScale = 1.5;
        _scrollView.minimumZoomScale = 1;
        
        _imageView = [[UIImageView alloc] initWithFrame:frame];
        
        [_scrollView addSubview:_imageView];
        [self addSubview:_scrollView];
    }
    return self;
}
- (void)setImageUrl:(MKImageInfosModel *)model
{
    CGFloat width = model.width.floatValue;
    CGFloat height = model.height.floatValue;
    [_imageView setFrame:CGRectMake(0, (SCREEN_HEIGHT - SCREEN_WIDTH * height/ width) / 2, SCREEN_WIDTH, SCREEN_WIDTH * height/ width)];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:model.current_img_url]];
    
    for (id view in self.subviews) {
        if ([view isKindOfClass:[PGView class]]) {
            [view removeFromSuperview];
        }
    }
    
    _progressView = [[PGView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    //        _progressView.hidden = YES;
    _progressView.backgroundColor = [UIColor clearColor];
    _progressView.center = self.center;
    [self insertSubview:_progressView atIndex:1];
    
    [_imageView sd_setImageWithURL:[NSURL URLWithString:model.current_img_url] placeholderImage:[UIImage imageNamed:@""] options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        //        _progressView.hidden = NO;
        if (expectedSize < 0) {
            expectedSize = 1;
        }
        CGFloat progress = receivedSize /((CGFloat)expectedSize);
        
        _progressView.progress = progress;
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        if(image!=nil && _progressView.progress <1.0f) {
            _progressView.progress = 1.0f;
            [_progressView removeFromSuperview];
            //            _scrollView.contentSize = _imageView.image.size;
        }
        
    }];

    
    _scrollView.contentSize = _imageView.image.size;
    
}

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
